package com.iefgames.cs.comet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import com.iefgames.cs.framework.exception.CometDisconnectException;
import com.iefgames.cs.manager.CsManager;
import com.iefgames.cs.utils.JsonUtil;

public class UsComet extends AbstractComet {
	Log logger = LogFactory.getLog(UsComet.class);
	
	@Override
	public void comet(HttpServletRequest request, HttpServletResponse response) {
		String usUuid = request.getParameter("uuid");
		if (usUuid == null
				|| usUuid.length() != 32
				|| usUuid.equals(StringUtils.EMPTY)) {
			return;
		}
		
		Continuation continuation = ContinuationSupport.getContinuation(request, null);
		if (continuation.isNew()) {
			initComet(request, response);
			newComet(usUuid, continuation);
		}

		fire(request, response);
		
		sleep(continuation);
	}
	
	@Override
	protected void initComet(HttpServletRequest request,
			HttpServletResponse response) {
		String csUuid = request.getParameter("csUuid");
		if (csUuid == null
				|| !CsManager.isOnline(csUuid)) {
			csUuid = CsManager.randomOnlineCSUuid();
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append(getHeadString());
		sb.append("<script type='text/javascript'>");
		sb.append("_('comet', '");
		sb.append(csUuid);
		sb.append("');");
		sb.append("</script>");
		
		PrintWriter writer = null;
		try {
			setNoCacheHeader(response);
			
			writer = response.getWriter();
			writer.println(sb.toString());
			writer.flush();
		} catch (IOException ioe) {
			if (writer != null) {
				writer.close();
			}
			
			//异常直接抛出
			throw new CometDisconnectException(request, response, ioe);
		}
	}

	@Override
	protected String output(Vector shouts) {
		StringBuffer sb = new StringBuffer();
		sb.append("<script type='text/javascript'>");
		sb.append("_('msg', ");
		sb.append(JsonUtil.toJs(shouts));
		sb.append(");");
		sb.append("</script>");
		return sb.toString();
	}

}
